import 'package:flutter/foundation.dart' show defaultTargetPlatform;
import 'package:flutter/services.dart' show MethodCall, MethodChannel;
import 'package:flutter/material.dart';
import 'src/platform_interface.dart';

class LiveChatWidget extends StatefulWidget {
  final String url;
  final VoidCallback? onClose;
  const LiveChatWidget({Key? key, required this.url, this.onClose})
      : super(key: key);

  @override
  State<LiveChatWidget> createState() => _LiveChatWidgetState();
}

class _LiveChatWidgetState extends State<LiveChatWidget> {
  NativeViewPlatform? _platform;
  var platforms = [];
  late MethodChannel channel;
  void _onPlatformViewCreated(int viewId) {
    channel = MethodChannel('flutter_comm100_$viewId');
    channel.setMethodCallHandler((MethodCall call) async {
      if (call.method == 'onClose') {
        widget.onClose?.call();
      }
    });
    platforms.add(channel);
  }

  @override
  Widget build(BuildContext context) {
    return Container(child: platform.build(context: context, url: widget.url));
  }

  @override
  void dispose() {
    channel.setMethodCallHandler(null);
    super.dispose();
  }

  NativeViewPlatform get platform {
    if (_platform == null) {
      switch (defaultTargetPlatform) {
        case TargetPlatform.android:
          _platform =
              MaterialCommWidget(onPlatformViewCreated: _onPlatformViewCreated);
          break;
        case TargetPlatform.iOS:
          _platform = CupertinoCommWidget(
              onPlatformViewCreated: _onPlatformViewCreated);
          break;
        default:
          throw UnsupportedError(
              "Trying to use the default comm100 view implementation for $defaultTargetPlatform but there isn't a default one");
      }
    }
    return _platform!;
  }
}
